package utils;

import java.util.Arrays;
import java.util.List;

public class EsUtil {

    private EsUtil() {
    }

    private static final List<String> SPECIAL_SIGN = Arrays.asList("@", "&", "*", "%", "#", "!", "~", "·", "(", ")", "-", "+", "=", "_", "'", ",");
    // 问号
    private static final String  QUESTION_MARK ="?";
    // 井号
    private static final String  POUND_SIGN ="#";

    /**
     * 处理特殊的关键字查询，（url 带？# 等）
     * @param keyword
     * @return
     */
    public static String getSpecialKeywordRange(String keyword){
        if(keyword.contains(QUESTION_MARK) && keyword.indexOf(QUESTION_MARK) >0){
            keyword = keyword.substring(0,keyword.indexOf(QUESTION_MARK));
        } else if (keyword.contains(POUND_SIGN) && keyword.indexOf(POUND_SIGN)>0){
            keyword = keyword.substring(0,keyword.indexOf(POUND_SIGN));
        }
        String keywordRange = ".*" + keyword + ".*";
        return  keywordRange ;
    }

    /**
     * 特殊字符转义，方法api工具类缺少"< >"
     * @param  keyward
     * @return
     */
    public static String escape(String keyward) {
        StringBuilder sb = new StringBuilder();

        for(int i = 0; i < keyward.length(); ++i) {
            char c = keyward.charAt(i);
            if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':' || c == '^' || c == '[' || c == ']'
                    || c == '"' || c == '{' || c == '}' || c == '~' || c == '*' || c == '?' || c == '|' || c == '&' || c == '/' || c == '<' || c == '>' ) {
                sb.append('\\');
            }

            sb.append(c);
        }

        return sb.toString();
    }

    public static String replaceSpecialKeyword(String keyword) {
        for (String sign : SPECIAL_SIGN) {
            if (keyword.contains(sign)) {
                keyword = keyword.replace(sign, " ");
            }
        }
        return keyword.trim();
    }
}
